package com.hanshg.cherry.service.impl.job;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hanshg.cherry.base.result.Results;
import com.hanshg.cherry.config.scheduler.CronTaskRegistrar;
import com.hanshg.cherry.config.scheduler.SchedulingRunnable;
import com.hanshg.cherry.mapper.job.JobMapper;
import com.hanshg.cherry.model.SysJob;
import com.hanshg.cherry.service.job.JobService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 工作服务impl
 *
 * @ClassName JobServiceImpl
 * @Description TODO
 * @Author 柠檬水
 * @Date 2020/4/20 11:59
 * @Version 1.0
 **/
@Service
@Transactional
@Slf4j
public class JobServiceImpl extends ServiceImpl<JobMapper, SysJob> implements JobService {

    private final CronTaskRegistrar cronTaskRegistrar;

    public JobServiceImpl(CronTaskRegistrar cronTaskRegistrar) {
        this.cronTaskRegistrar = cronTaskRegistrar;
    }

    @Override
    public Results<SysJob> saveJob(SysJob sysJob) {
        boolean success = saveOrUpdate(sysJob);
        if (!success) {
            return Results.failure();
        } else {
            //成功
            SchedulingRunnable task = new SchedulingRunnable(sysJob.getBeanName(), sysJob.getMethodName(), sysJob.getMethodParam());
            if (sysJob.getStatus().equals(SysJob.Status.NORMAL)) {
                cronTaskRegistrar.addCronTask(task, sysJob.getCron());
            }
            log.info("saveJob......"+sysJob);
        }
        return Results.success();
    }

    @Override
    public Results<SysJob> updateJob(SysJob sysJob) {
        boolean success = updateById(sysJob);
        if (!success) {
            return Results.failure();
        } else {
            //成功
            SchedulingRunnable task = new SchedulingRunnable(sysJob.getBeanName(), sysJob.getMethodName(), sysJob.getMethodParam());
            if (sysJob.getStatus().equals(SysJob.Status.NORMAL)) {
                cronTaskRegistrar.removeCronTask(task);
                cronTaskRegistrar.addCronTask(task, sysJob.getCron());
            } else {
                cronTaskRegistrar.removeCronTask(task);
            }
            log.info("updateJob......."+sysJob);
        }
        return Results.success();
    }

    @Override
    public Results<SysJob> deleteJob(SysJob sysJob) {
        SysJob exitSysJOb = getById(sysJob.getId());
        boolean success = removeById(sysJob.getId());
        if (!success) {
            return Results.failure();
        } else {
            //成功
            SchedulingRunnable task = new SchedulingRunnable(exitSysJOb.getBeanName(), exitSysJOb.getMethodName(), exitSysJOb.getMethodParam());
            if (exitSysJOb.getStatus().equals(SysJob.Status.NORMAL)) {
                cronTaskRegistrar.removeCronTask(task);
            }
            log.info("deleteJob........"+sysJob);
        }
        return Results.success();
    }
}
